import { PlayBookApi } from '@/api'
import { formatDataBeforeCommit } from '@/components/WorkFlow/utils'
import YAML from 'yaml'

const getYamlData = wfData => {
  let formatGraph = {}
  if (wfData.graphData) {
    formatGraph = formatDataBeforeCommit(wfData.graphData)
  }
  return YAML.stringify({
    version: '2.0',
    [wfData.name]: {
      description: wfData.description,
      runner: 'workflow',
      type: 'direct',
      tags: wfData.tags,
      ...formatGraph
    }
  })
}
export class PlayBookService {
  static queryNodeList(params) {
    return PlayBookApi.queryAPPList(params).then(({ data: { items } }) => {
      return { data: items }
    })
  }
  static createInstance(data) {
    return PlayBookApi.createInstance(data).then(res => {
      return {
        instance_id: res.data.id
      }
    })
  }
  static updateInstance(data) {
    return PlayBookApi.updateInstance(data).then(res => {
      return {
        instance_id: res.data.id
      }
    })
  }
  static createPlay(data) {
    const { wf_data, is_publish } = data
    return PlayBookApi.createPlay({
      yaml_data: getYamlData(wf_data),
      wf_data,
      is_publish
    })
  }
  static updatePlay(data) {
    const { id, wf_data, is_publish } = data
    return PlayBookApi.updatePlay({
      id,
      yaml_data: getYamlData(wf_data),
      wf_data,
      is_publish
    })
  }
  static deletePlay({ ids }) {
    return PlayBookApi.deletePlay({ ids: ids.join() })
  }
  static queryPlayList(data) {
    return PlayBookApi.queryPlayList({
      ...data,
      page: data.offset / data.limit + 1,
      offset: undefined,
      random: undefined
    }).then(({ data = {} }) => {
      return {
        data: data.items,
        total: data.total
      }
    })
  }
  static queryPlayAllList() {
    return PlayBookApi.queryPlayList({
      page: undefined,
      limit: undefined
    }).then(({ data = { items: [], total: 0 } }) => {
      const list = data.items?.map(
        ({ id, name, schemas: { properties, required } }) => {
          // 须调度时赋值的变量集合
          let input = []
          for (const key in properties) {
            const {
              defined = false,
              display,
              type,
              required = false
            } = properties[key]
            if (defined) {
              input.push({
                label: display,
                value: key,
                type,
                required
              })
            }
          }
          return {
            label: name,
            value: id,
            input
          }
        }
      )
      return { data: list }
    })
  }
}
